<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX GET Request</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <button id="downloadButton">下载文件</button>
    <div id="message"></div>

    <script>
        $(document).ready(function () {
            $('#downloadButton').click(function () {
            const url = 'http://localhost:5200/Export/ClosedXML';
                $.ajax({
                    url: url,
                    method: 'GET',
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function (blob, status, xhr) {
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;

                        const contentDisposition = xhr.getResponseHeader('Content-Disposition');
                        if (contentDisposition) {
                            const regex = /filename\*?=([^;]+)/i;
                            const match = contentDisposition.match(regex);
                            if (match) {
                                let filename = match[1];
                                if (filename.startsWith('UTF-8\'\'')) {
                                    filename = decodeURIComponent(filename.slice(7));
                                } else {
                                    filename = filename.replace(/^"|"$/g, '');
                                }
                                a.download = filename;
                            }
                        } else {
                            a.download = 'downloaded_file';
                        }
                        a.click();
                        window.URL.revokeObjectURL(url);

                        // 成功提示
                        alert('文件下载成功！');
                        // $('#message').html('文件下载成功！');
                    },
                    error: function (error) {
                        // 错误提示
                        alert(`下载失败，错误码: ${error.status}`);
                        // $('#message').html(`下载失败，错误码: ${error.status}`);
                    }
                });
            });
        });
    </script>
</body>

</html>